<script setup lang="ts">
import { onMounted, ref, onUnmounted, watch } from 'vue'
import gsap from 'gsap'
import { Observer } from 'gsap/Observer'

gsap.registerPlugin(Observer)

interface CarouselItem {
  id: number
  content: string | number
  imageUrl?: string
  text?: string
}

const carouselItems = ref<CarouselItem[]>([
  { id: 1, content: '1', imageUrl: 'http://125.122.29.223:8005/park/home/risk.png', text: 'http://125.122.29.223:8005/park/home/risk-t.png' },
  { id: 2, content: '2', imageUrl: 'http://125.122.29.223:8005/park/home/risk.png', text: 'http://125.122.29.223:8005/park/home/screen-t.png' },
  { id: 3, content: '8', imageUrl: 'http://125.122.29.223:8005/park/home/risk.png', text: 'http://125.122.29.223:8005/park/home/emergy-t.png' }
])

const progress = ref(0)
const radius = 242
const carouselRef = ref<HTMLElement | null>(null)
let autoAnimation: gsap.core.Tween | null = null
let resumeTimeout: any
let isUserInteracting = ref(false)
let manualAnimation: gsap.core.Tween | null = null
let lastProgressValue = 0
let observer: Observer | null = null
let animateFunc: (() => void) | null = null

const handleMouseEnter = (item: CarouselItem) => {
  if (autoAnimation) {
    autoAnimation.pause()
    console.log('暂停动画，当前悬停在 carousel-image:', item.id, item.content)
  }
}

const handleMouseLeave = () => {
  if (autoAnimation && !isUserInteracting.value) {
    autoAnimation.resume()
    console.log('恢复动画')
  }
}

const startAutoRotation = (fromValue?: number) => {
  if (autoAnimation) autoAnimation.kill()

  const startValue = fromValue !== undefined ? fromValue : progress.value
  const endValue = startValue + 1 // 旋转一圈

  autoAnimation = gsap.to(progress, {
    value: endValue,
    duration: 10,
    ease: 'none',
    modifiers: {
      value: (v) => v % 1 // 确保值在0-1之间循环
    },
    onComplete: () => {
      // 一圈完成后继续下一圈
      startAutoRotation(progress.value)
    }
  })
}

const scheduleAutoResume = () => {
  if (resumeTimeout) clearTimeout(resumeTimeout)
  isUserInteracting.value = true

  resumeTimeout = setTimeout(() => {
    isUserInteracting.value = false
    if (!manualAnimation?.isActive()) {
      lastProgressValue = progress.value
      startAutoRotation(lastProgressValue)
      console.log('从当前位置恢复自动动画，progress:', lastProgressValue)
    }
  }, 1500)
}

const initCarousel = () => {
  if (!carouselRef.value) return

  // 清理之前的资源
  if (observer) observer.kill()
  if (autoAnimation) autoAnimation.kill()
  if (manualAnimation) manualAnimation.kill()
  if (animateFunc) gsap.ticker.remove(animateFunc)
  if (resumeTimeout) clearTimeout(resumeTimeout)

  animateFunc = () => {
    const images = document.querySelectorAll('.carousel-image')
    images.forEach((image, index) => {
      const theta = (index / images.length - progress.value) * Math.PI * 2
      const x = -Math.sin(theta) * radius
      const z = Math.cos(theta) * radius - 50

      gsap.set(image, {
        x: x,
        y: 0,
        z: z,
        rotationY: 0,
        rotationX: 0,
        transformStyle: 'preserve-3d',
        transformOrigin: 'center center'
      })
    })
  }

  observer = Observer.create({
    target: carouselRef.value,
    type: "wheel,pointer",
    onPress: () => {
      if (!carouselRef.value) return
      carouselRef.value.style.cursor = 'grabbing'
      if (autoAnimation) autoAnimation.pause()
      isUserInteracting.value = true
    },
    onRelease: () => {
      if (!carouselRef.value) return
      carouselRef.value.style.cursor = 'grab'
      scheduleAutoResume()
    },
    onChange: (self) => {
      if (manualAnimation?.isActive()) manualAnimation.kill()

      const p = self.event.type === 'wheel' ? self.deltaY * -0.0003 : self.deltaX * 0.003
      manualAnimation = gsap.to(progress, {
        value: `+=${p}`,
        duration: 0.5,
        ease: 'power2.out',
        onUpdate: () => {
          isUserInteracting.value = true
          if (animateFunc) animateFunc()
        },
        onComplete: scheduleAutoResume
      })

      scheduleAutoResume()
    }
  })

  gsap.ticker.add(animateFunc)
  startAutoRotation()
}

onMounted(() => {
  initCarousel()
})

onUnmounted(() => {
  // 清理所有资源
  if (observer) observer.kill()
  if (autoAnimation) autoAnimation.kill()
  if (manualAnimation) manualAnimation.kill()
  if (animateFunc) gsap.ticker.remove(animateFunc)
  if (resumeTimeout) clearTimeout(resumeTimeout)
})

// 如果使用keep-alive，可以添加以下代码
// 当组件从缓存中恢复时重新初始化
onActivated(() => {
  initCarousel()
})

// 当组件被缓存时清理资源
onDeactivated(() => {
  if (observer) observer.kill()
  if (autoAnimation) autoAnimation.kill()
  if (manualAnimation) manualAnimation.kill()
  if (animateFunc) gsap.ticker.remove(animateFunc)
  if (resumeTimeout) clearTimeout(resumeTimeout)
})
</script>

<template>
  <!-- 保持原有模板不变 -->
  <div class="carousel-container">
    <div class="demo-bg">
      <div ref="carouselRef" class="carousel">
        <div v-for="(item, index) in carouselItems" :key="item.id" class="carousel-image"
          @mouseenter="handleMouseEnter(item)" @mouseleave="handleMouseLeave()">
          <div class="w-full h-full flex justify-center items-center flex-col">

            <img v-if="item.text" :src="item.text" class="carousel-img " alt="Carousel item">
            <img v-if="item.imageUrl" :src="item.imageUrl" class="carousel-img mb-[30px]" alt="Carousel item">

          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
/* 保持原有样式不变 */
.carousel-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #0c1d38;
}

.demo-bg {
  width: 500px;
  height: 300px;
  background: url('http://125.122.29.223:8005/park/home/dz-q.png') no-repeat;
  background-size: 100% 100%;
  position: relative;
}

.carousel {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  transform: rotateX(-34deg) translateY(-70px);
  transform-style: preserve-3d;
  perspective: 600px;
  user-select: none;
  cursor: grab;
  position: relative;

  &-image {
    position: absolute;
    width: 100px;
    height: 100px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
    transform-origin: center center;
    background-image: url('http://125.122.29.223:8005/park/home/dz-item.png');
    background-size: 100% 100%;
    backface-visibility: visible;
    will-change: transform;
    transform-style: preserve-3d;
    transition: transform 0.1s linear;

    span {
      font-size: 24px;
      font-weight: bold;
      transform: translateZ(20px);
    }
  }

  &-img {
    width: 50px;
    height: 50px;
    object-fit: contain;
    transform: translateZ(20px);
  }
}

@media (max-width: 600px) {
  .demo-bg {
    width: 100%;
    padding-bottom: 60%;
    height: auto;
  }

  .carousel {
    transform: rotateX(-10deg) scale(0.6) translateY(-60px);
  }
}
</style>